package com.trust.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtil {

    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        // 从xml配置文件中创建SqlSessionFactory
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        // 声明InputStream，并在try块外初始化为null
        InputStream resourceAsStream = null;

        try {
            // 使用Resources类的静态方法获取配置文件流
            resourceAsStream = Resources.getResourceAsStream("config.xml");
            // 【关键修正】去掉类型声明，直接赋值给类变量，避免变量遮蔽
            sqlSessionFactory = builder.build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static SqlSession getSqlsession() {
        // 【关键修正】通过sqlSessionFactory实例调用openSession()方法
        return sqlSessionFactory.openSession();
    }
}